import { Handlers } from "$fresh/server.ts";

export const handler: Handlers = {
  GET(_, ctx) {
    const code = ctx.url.searchParams.get("code");
    if (!code) {
      return new Response(JSON.stringify({
        code: 400,
        message: "code is required",
      }));
    }
    const searchParams = new URLSearchParams();
    searchParams.set("client_id", Deno.env.get("AUTHING_APP_ID")!);
    searchParams.set("client_secret", Deno.env.get("AUTHING_SECRET_KEY")!);
    searchParams.set("grant_type", "authorization_code");
    searchParams.set(
      "redirect_uri",
      "https://xjm.deno.dev/api/authing/parsecode",
    );
    searchParams.set("code", code);
    console.log(JSON.stringify({
      "Content-Type": "application/x-www-form-urlencoded",
      "x-authing-app-id": Deno.env.get("AUTHING_APP_ID")!,
    }));
    const url = new URL("/oidc/token", Deno.env.get("ADMIN_AUTHING_DOMAIN"));
    return fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "x-authing-app-id": Deno.env.get("AUTHING_APP_ID")!,
      },
      body: searchParams.toString(),
    }).then(async (r) => {
      return new Response(await r.text());
    }, (e) => {
      return new Response(e.message, { status: 500 });
    });
    /* const sdk = getResumeAuthingSDK();

    // 认证参数拼装
    return sdk.getAccessTokenByCode(code).then((result) => {
      setRefreshToken(result.refresh_token);
      sdk.getUserInfoByAccessToken(result.id_token)
        .then((resp) => {
          return storeUserInfo(result.id_token, resp);
        });
      return new Response(JSON.stringify(result));
    }, (e) => {
      console.error(e.message);

      return new Response("页面出错,", { status: 500 });
    }); */
  },
};
